#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#ifndef WIN32
  #include <sys/time.h>
  #include <unistd.h>
#else
  #include <time.h>
#endif

#include "lo/lo.h"
#include "TuioDumper/MTouchware_dump_handlers.h"


#define DEFAULT_TUIO_IN_PORT "3333"

void error(int num, const char *msg, const char *path);
void read_stdin(void);

void usage()
{
    printf("usage : TuioDumper [dumpfilename] [inport]\n");
    return;
}

int done=0;

int main(int argc, char *argv[])
{
    int     lo_fd;
    fd_set  rfds;
    struct  timeval tv;
    int     retval;
    char    nf_inport[10];
    FILE   *nf_dumpfile;
    char    nf_dumpfilename[100];

    strcpy(nf_dumpfilename,"../../logs/dump.tuio");
    strcpy(nf_inport, DEFAULT_TUIO_IN_PORT);


    if((argc>3)||((argc==2)&&(strcmp(argv[1],"--help")==0)))
    {
            usage();
            return 0;
    }
    else if (argc==2)
    {
            strcpy(nf_dumpfilename,argv[1]);
    }
    else if (argc==3)
    {
            strcpy(nf_dumpfilename,argv[1]);
            strcpy(nf_inport,argv[2]);
    }


    nf_dumpfile=fopen(nf_dumpfilename,"wt");

    if (!nf_dumpfile)
    {
            printf("error while opening %s for writing\n",nf_dumpfilename);
            exit(-1);
    }

    printf("Recording port %s to file %s. Press 'q' then enter to exit.\n",nf_inport, nf_dumpfilename);

    /* start a new server on port TUIO_IN_PORT */
    lo_server s = lo_server_new(nf_inport, error);

    /* add method that will match any path and args */
    lo_server_add_method(s, NULL, NULL, generic_dumper, (void *)nf_dumpfile);

    /* get the file descriptor of the server socket, if supported */
    lo_fd = lo_server_get_socket_fd(s);

    if (lo_fd > 0) {

        /* select() on lo_server fd is supported, so we'll use select()
         * to watch both stdin and the lo_server fd. */

        do {
            FD_ZERO(&rfds);
#ifndef WIN32
            FD_SET(0, &rfds);  /* stdin */
#endif
            FD_SET(lo_fd, &rfds);

            retval = select(lo_fd + 1, &rfds, NULL, NULL, NULL); /* no timeout */

            if (retval == -1) {

                printf("select() error\n");
                exit(1);

            } else if (retval > 0) {

                if (FD_ISSET(0, &rfds)) {

                    read_stdin();

                }
                if (FD_ISSET(lo_fd, &rfds)) {

                    lo_server_recv_noblock(s, 0);

                }
            }

        } while (!done);

    } else {

        /* lo_server protocol does not support select(), so we'll watch
         * stdin while polling the lo_server. */
#ifdef WIN32
        printf("non-blocking input from stdin not supported under Windows\n");
        exit(1);
#else
        do {

            FD_ZERO(&rfds);
            FD_SET(0, &rfds);
            tv.tv_sec = 0;
            tv.tv_usec = 10000;

            retval = select(1, &rfds, NULL, NULL, &tv); /* timeout every 10ms */

            if (retval == -1) {

                printf("select() error\n");
                exit(1);

            } else if (retval > 0 && FD_ISSET(0, &rfds)) {

                read_stdin();

            }

            lo_server_recv_noblock(s, 0);

        } while (!done);
#endif
    }
    fflush(nf_dumpfile);
    fclose(nf_dumpfile);
    return 0;
}

void error(int num, const char *msg, const char *path)
{
    printf("liblo server error %d in path %s: %s\n", num, path, msg);
}


void read_stdin(void)
{
    char buf[256];
    int len = read(0, buf, 256);
    if (len > 0) {
        printf("stdin: ");
        fwrite(buf, len, 1, stdout);
        printf("\n");
        fflush(stdout);

        if(buf[0]=='q')
        {
                done=1;
        }
    }
}
